<?php
/**
 * Created by Phpstorm
 * User: 一个猫
 * Date: 2023/11/22
 * Time: 13:57
 */

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\AuthorizationRequest;
use App\Models\BusinessMember;
use App\Server\WeChatServer;
use Illuminate\Http\Request;

class AuthorizationsController extends Controller
{
    public function store(AuthorizationRequest $request)
    {
        $validated = $request->validated();

        // 账号密码校验
        $token = (new BusinessMember())->login($validated['username'], $validated['password']);
        if ($token === false) {
            return response()->json([
                'data' => [],
                'message' => '账号或密码错误！',
                'code' => -1
            ]);
        }

        // 获取用户等级信息
        $memberInfo = BusinessMember::with('position')
            ->where('username', $validated['username'])
            ->first();

        return response()->json([
            'data' => [
                'token' => $token,
                'member_position' => $memberInfo->position->level
            ],
            'message' => '请求成功！',
            'code' => 200
        ]);
    }

    // 小程序登录 todo by tinkle
    public function wxLogin()
    {

    }

    // 微信小程序授权
    public function wxEmpower(Request $request)
    {
        $code = $request->post('code');

        $sever = new WeChatServer();
        $res = $sever->app->auth->session($code);

        return response()->json([
            'data' => [
                'wx' => $res,
            ],
            'message' => '请求成功！',
            'code' => 200
        ]);
    }
}
